import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import Authorized from 'components/common/authorized'

import { Form, message, Popconfirm, Button, Switch } from 'antd'
import { widgetType } from 'constants'
import PropTypes from 'prop-types'
import AddModal from './com/addModal'
import EditPassword from './com/editPasswordModal'
import StaffEditModal from './com/editModal'
import actions from 'actions/setup'
import Style from './list.css'

class ListForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getStaffList: PropTypes.func,
    staffData: PropTypes.object,
    delRequest: PropTypes.any,
    delStaff: PropTypes.func,
    departmentList: PropTypes.any,
    getDepartmentList: PropTypes.func,
    createRequest: PropTypes.any,
    createStaffAccount: PropTypes.func,
    editStaffStatus: PropTypes.func,
    editStaffStatusRequest: PropTypes.any,
    editStaffPasswordRequest: PropTypes.any,
    editStaffPassword: PropTypes.func,
    getRoleListOptions: PropTypes.func,
    roleOptions: PropTypes.any,
    // getStaffDetail: PropTypes.func,
    staffDetail: PropTypes.any,
    editStaffInfo: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      showEditModal: false,
      showEdditPassword: false,
      showAddModal: false,
      staffDetail: {}
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.handleAddCancel = this.handleAddCancel.bind(this)
    this.handleAddOk = this.handleAddOk.bind(this)
    this.handleEditPasswordCancel = this.handleEditPasswordCancel.bind(this)
    this.handleEditPasswordOk = this.handleEditPasswordOk.bind(this)
  }

  getFilterCols (departmentList) {
    return [
      {
        label: '输入搜索',
        id: 'searchField',
        widget: widgetType.input,
        placeholder: '请输入'
      }, {
        label: '所属部门',
        id: 'deptId',
        widget: widgetType.select,
        placeholder: '请选择分类',
        options: departmentList
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '成员账号',
        dataIndex: 'workNumber',
        key: 'workNumber',
        width: 100
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        width: 100

      },
      {
        title: '邮箱地址',
        dataIndex: 'email',
        key: 'email',
        width: 100

      },
      {
        title: '所属部门',
        dataIndex: 'deptName',
        key: 'deptName',
        width: 100
      },
      {
        title: '添加时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 100,
        sorter: (a, b) => a.createTime - b.createTime
      },
      {
        title: '最后登陆',
        dataIndex: 'loginTime',
        key: 'loginTime',
        width: 100,
        sorter: (a, b) => a.loginTime - b.loginTime
      },
      {
        title: '是否启用',
        dataIndex: 'status',
        key: 'status',
        width: 100,
        render: (text, row) => <Switch defaultChecked={text === 0} onChange={(e) => this.handleUpdate(row.userId, e)} />
      },
      {
        title: '操作',
        dataIndex: 'a',
        key: 'a',
        render: (text, record) => {
          return <>
            <div>
              {/* <a className={Style['a-btn']} onClick={() => this.handleRestore(record.userId)}>部门设置</a> */}
              <a className={Style['a-btn']} onClick={(e) => this.handleRestore(e, record)}>编辑</a>
            </div>
            <div>

              <Authorized auth='SETTING:RULES:MEMBER:DEL'>
                <Popconfirm placement='top' title='确认是否删除成员' onConfirm={() => this.handleDelete(record.userId)}>
                  <a className={Style['a-btn']}>删除</a>
                </Popconfirm>
              </Authorized>
              <a className={Style['a-btn']} onClick={() => this.handleEditPassword(record)}>账户设置</a>

            </div>
          </>
        },
        width: 100
      }
    ]
  }

  handleRestore = (e, record) => {
    // this.props.getStaffDetail({
    //   userId: record.userId
    // }).then(res => {
    // })
    actions.getStaffDetail({
      userId: record.userId
    }).then(res => {
      this.setState({
        showEditModal: true,
        staffDetail: res.data
      })
    })
  }

  handleEditModalCancel = () => {
    this.setState({ showEditModal: false })
  }

  handleUpdate (id, value) {
    this.props.editStaffStatus({
      userId: id,
      status: value ? 0 : -1
    })
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    this.props.getStaffList({
      pageNo: 1,
      pageSize: 20
    })
  }
  search (values = {}) {
    const { pageSize, pageNo } = this.state
    values.pageNo = pageNo
    values.pageSize = pageSize
    this.setState({
      params: {}
    })
    this.props.getStaffList(values)
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getStaffList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getStaffList(params)
  }

  handleDelete (userId) {
    this.props.delStaff({
      userId
    })
  }

  handleAdd () {
    this.setState({
      showAddModal: true
    })
  }

  handleAddCancel () {
    this.setState({
      showAddModal: false
    })
  }

  handleAddOk (values) {
    this.props.createStaffAccount(values)
  }

  handleEditPassword (user) {
    this.setState({
      showEdditPassword: true,
      user
    })
  }

  handleEditPasswordCancel () {
    this.setState({
      showEdditPassword: false
    })
  }

  handleEditPasswordOk (values) {
    this.props.editStaffPassword(values)
    this.setState({
      showEdditPassword: false
    })
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    this.props.getStaffList({
      pageSize,
      pageNo
    })
    this.props.getDepartmentList()
    this.props.getRoleListOptions()
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.delRequest && nextProps.delRequest) {
      message.success('删除成功')
      this.search()
    }
    if (!this.props.createRequest && nextProps.createRequest) {
      message.success('添加成功')
      this.search()
    }
    if (!this.props.editStaffPasswordRequest && nextProps.editStaffPasswordRequest) {
      message.success('修改成功')
      this.search()
    }
  }

  confirmEditModal = values => {
    this.props.editStaffInfo(values).then(() => {
      this.setState({
        showEditModal: false
      })
      this.reset()
    })
  }

  render () {
    const { pageNo, pageSize, showAddModal, showEdditPassword, user, showEditModal, staffDetail } = this.state
    const { form, staffData, departmentList, roleOptions } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: staffData && staffData.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange

    }
    return (
      <>
        <ContentBox>
          <div>
            <Filters cols={this.getFilterCols(departmentList)} form={form} search={this.search} reset={this.reset}>
              <Button type='primary' onClick={() => this.handleAdd()}>添加</Button>
            </Filters>
            <CustomTable loading={!staffData} columns={this.getTableCols()} dataSource={(staffData && staffData.list) || []} pagination={pagination} />
            <AddModal handleAddOk={this.handleAddOk} handleAddCancel={this.handleAddCancel} visible={showAddModal} departmentList={departmentList} roleOptions={roleOptions} />
            <EditPassword handleEditPasswordOk={this.handleEditPasswordOk} handleEditPasswordCancel={this.handleEditPasswordCancel} visible={showEdditPassword} user={user} />
            {(staffDetail && staffDetail.userId) ? <StaffEditModal
              visible={showEditModal}
              detail={staffDetail || {}}
              departmentList={departmentList}
              roleOptions={roleOptions}
              onOk={this.confirmEditModal}
              onCancel={this.handleEditModalCancel}
            /> : null}
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  staffData: state.setup.staffData,
  delRequest: state.setup.delRequest,
  departmentList: state.setup.departmentList || [],
  createRequest: state.setup.createRequest,
  editStaffStatusRequest: state.setup.editStaffStatusRequest,
  editStaffPasswordRequest: state.setup.editStaffPasswordRequest,
  roleOptions: state.setup.roleOptions
  // staffDetail: state.setup.staffDetail
})
const mapDispatch = dispatch => ({
  getStaffList: dispatch.setup.getStaffList,
  restoreReply: dispatch.setup.restoreReply,
  delStaff: dispatch.setup.delStaff,
  getDepartmentList: dispatch.setup.getDepartmentList,
  createStaffAccount: dispatch.setup.createStaffAccount,
  editStaffStatus: dispatch.setup.editStaffStatus,
  editStaffPassword: dispatch.setup.editStaffPassword,
  getRoleListOptions: dispatch.setup.getRoleListOptions,
  // getStaffDetail: dispatch.setup.getStaffDetail,
  editStaffInfo: dispatch.setup.editStaffInfo
})

const List = Form.create()(ListForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(List)
)
